package com.lenovo.manufacture;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.lenovo.manufacture.model.CarInfo;
import com.lenovo.manufacture.model.ProductionLine;
import com.lenovo.manufacture.model.UserProductionLine;
import com.lenovo.manufacture.model.UserQuestionCar;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Race5Activity extends AppCompatActivity {

    private ListView list_five;
    private LinearLayout five_lv;
    private List<UserQuestionCar.DataBean> userQuestionCars = new ArrayList<>();
    private List<Car> carList = new ArrayList<>();
    private ArrayAdapter<Car> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_five);

        try {
            initView();
            getUserQuestionCars();
        } catch (Exception e) {
            Log.e("Race5Activity", e.getLocalizedMessage(), e);
        }

    }

    private void getUserQuestionCars() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://192.168.1.103:8085/dataInterface/UserQuestion/getAll")
                .method("POST", body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(Race5Activity.this, "失败" + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    UserQuestionCar userQuestionCar = new Gson().fromJson(response.body().string(), UserQuestionCar.class);
                    if (userQuestionCar.getData().isEmpty()) {
                        runOnUiThread(() -> Toast.makeText(Race5Activity.this, "userQuestionCar.getData().isEmpty()" + response.code(), Toast.LENGTH_SHORT).show());
                    } else {
                        userQuestionCars.clear();
                        userQuestionCars.addAll(userQuestionCar.getData());
                        getUserProductionLine();
                    }

                } else {
                    runOnUiThread(() -> Toast.makeText(Race5Activity.this, "失败" + response.code(), Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void getUserProductionLine() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        for (int i = 0; i < userQuestionCars.size(); i++) {
            Car car = new Car();
            car.id = userQuestionCars.get(i).getId();
            carList.add(car);
            final int index = i;
            final int userProductionLineId = userQuestionCars.get(i).getUserProductionLineId();
            RequestBody body = RequestBody.create(mediaType, "id=" + userProductionLineId);
            Request request = new Request.Builder()
                    .url("http://192.168.1.103:8085/dataInterface/UserProductionLine/getInfo")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        UserProductionLine userProductionLine = new Gson().fromJson(response.body().string(), UserProductionLine.class);
                        UserProductionLine.DataBean dataBean = userProductionLine.getData().get(0);
                        if (dataBean != null) {
                            getProductionLine(index, dataBean.getProductionLineId());
                        }
                    }

                }
            });
        }


    }

    private void getCarInfo() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        for (int i = 0; i < userQuestionCars.size(); i++) {
            final int index = i;
            RequestBody body = RequestBody.create(mediaType, "id=" + userQuestionCars.get(i).getCarId());
            Request request = new Request.Builder()
                    .url("http://192.168.1.103:8085/dataInterface/CarInfo/getInfo")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        CarInfo carInfo = new Gson().fromJson(response.body().string(), CarInfo.class);
                        CarInfo.DataBean dataBean = carInfo.getData().get(0);
                        Car car = carList.get(index);
                        car.fixPay = dataBean.getRepairGold();
                        runOnUiThread(()-> adapter.notifyDataSetChanged());
                    }
                }
            });
        }
    }

    private void getProductionLine(int i, int productionLineId) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "id=" + productionLineId);
        Request request = new Request.Builder()
                .url("http://192.168.1.103:8085/dataInterface/ProductionLine/getInfo")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    ProductionLine productionLine = new Gson().fromJson(response.body().string(), ProductionLine.class);
                    Car car = carList.get(i);
                    car.lineInfo = productionLine.getData().get(0).getProductionLineName();
                    car.content = productionLine.getData().get(0).getContent();
                    //
                    getCarInfo();
                    //runOnUiThread(() -> adapter.notifyDataSetChanged());
                }
            }
        });
    }

    private void initView() {
        list_five = (ListView) findViewById(R.id.list_five);
        five_lv = (LinearLayout) findViewById(R.id.five_lv);
        adapter = new ArrayAdapter<Car>(this, R.layout.item_five_lv, carList) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_five_lv, parent, false);
                ViewHolder viewHolder = new ViewHolder(convertView);
                Car item = getItem(position);
                viewHolder.tv_five_lv_id.setText("" + item.id);
                viewHolder.tv_five_lv_cardescribe.setText(item.content);
                viewHolder.tv_five_lv_cartype.setText(item.content);
                viewHolder.tv_five_lv_costs.setText("" + item.fixPay);
                viewHolder.tv_five_lv_information.setText(item.lineInfo);
                return convertView;
            }
        };
        list_five.setAdapter(adapter);
    }

    static class Car {
        int id = 0;
        String type = "null";
        String content = "null";
        String lineInfo = "null";
        int fixPay = 0;
    }

    static class ViewHolder {
        public View rootView;
        public TextView tv_five_lv_id;
        public TextView tv_five_lv_cartype;
        public TextView tv_five_lv_cardescribe;
        public TextView tv_five_lv_information;
        public TextView tv_five_lv_costs;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tv_five_lv_id = (TextView) rootView.findViewById(R.id.tv_five_lv_id);
            this.tv_five_lv_cartype = (TextView) rootView.findViewById(R.id.tv_five_lv_cartype);
            this.tv_five_lv_cardescribe = (TextView) rootView.findViewById(R.id.tv_five_lv_cardescribe);
            this.tv_five_lv_information = (TextView) rootView.findViewById(R.id.tv_five_lv_information);
            this.tv_five_lv_costs = (TextView) rootView.findViewById(R.id.tv_five_lv_costs);
        }

    }
}
